package com.rookie.im.learn.io.netty.heartbeat.client;

import com.rookie.im.learn.io.netty.heartbeat.handler.HeartBeatClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Random;

public class SimpleClient {
    public static void main(String[] args) {
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(loopGroup).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("decode", new StringDecoder());
                            socketChannel.pipeline().addLast("encode", new StringEncoder());
                            socketChannel.pipeline().addLast(new HeartBeatClientHandler());
                        }
                    });
            System.out.println("netty client start ...");
            Channel channel = bootstrap.connect("127.0.0.1", 9000).sync().channel();

            String text = "Netty Heartbeat";
            Random random = new Random();
            while(channel.isActive()) {
                int num = random.nextInt(8);
                System.out.println(num);
                Thread.sleep(num*1000);
                channel.writeAndFlush(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            loopGroup.shutdownGracefully();
        }
    }
}
